//
//  ManSelectDateTimeVC.swift
//  ManGuangDB
//
//  Created by 李东 on 2024/3/27.
//

import UIKit
import FSCalendar

class ManSelectDateTimeVC: UIViewController {
    
    @IBOutlet weak var bgView: UIView!
    
    @IBOutlet weak var dateBtn: UIButton!
    @IBOutlet weak var timeBtn: UIButton!
    @IBOutlet weak var calenderBgView: UIView!
    
    @IBOutlet weak var nextMonth: UIButton!
    @IBOutlet weak var lastMonth: UIButton!
    @IBOutlet weak var yearMonthLabel: UILabel!
    @IBOutlet weak var calender: FSCalendar!
    
    @IBOutlet weak var timeBgView: UIView!
    @IBOutlet weak var timePickerView: UIPickerView!
    
    var pickerIndex1 = 0
    var pickerIndex2 = 0
    var currentTs: Int = 0
    var currentDate: Date!
    
    var selectCallBack:((Int, String) -> Void)?
    lazy var gregorian = NSCalendar(identifier: .gregorian)

    
    init(ts: Int = 0) {
        super.init(nibName: nil, bundle: nil)
        self.currentTs = ts
    }
    

    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        view.backgroundColor = .black.withAlphaComponent(0.5)
       
        currentDate = Date()
        if currentTs != 0 {
            currentDate = Date(timeIntervalSince1970: TimeInterval(currentTs))
        }
        let ss = df1.string(from: currentDate).components(separatedBy: " ")
        dateBtn.setTitle(ss[0], for: .normal)
        timeBtn.setTitle(ss[1], for: .normal)
        yearMonthLabel.text = df2.string(from: currentDate)
      
        timePickerView.delegate = self
        timePickerView.dataSource = self
        initCalender()

    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        bgView.jw_corner(byRoundingCorners: [.topLeft, .topRight], radii: 20)
    }
    
    func initCalender() {
        calender.placeholderType = .none
        calender.delegate = self
        calender.dataSource = self
        calender.headerHeight = 0
        calender.weekdayHeight = 40
        calender.allowsMultipleSelection = false
//        calender.firstWeekday = 2
        calender.rowHeight = 45
        calender.appearance.weekdayFont = UIFont.systemFont(ofSize: 12)
        calender.appearance.weekdayTextColor = .white
        calender.appearance.titleFont = UIFont.systemFont(ofSize: 14)
        calender.appearance.titleDefaultColor = .white
        calender.appearance.todayColor = .clear
        calender.appearance.titleTodayColor = .white
        calender.locale = Locale.init(identifier: "zh_CN")
        calender.appearance.caseOptions = .weekdayUsesUpperCase
    }
    
    
    @IBAction func selectDateHandle(_ sender: Any) {
        calenderBgView.isHidden = false
        timeBgView.isHidden = true
        dateBtn.backgroundColor = UIColor.init(hex: 0xFFB429)
        timeBtn.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        dateBtn.setTitleColor(UIColor.black, for: .normal)
        timeBtn.setTitleColor(UIColor.white, for: .normal)
    }
    
    func showTimeView()  {
        calenderBgView.isHidden = true
        timeBgView.isHidden = false
        dateBtn.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        timeBtn.backgroundColor = UIColor.init(hex: 0xFFB429)
        dateBtn.setTitleColor(UIColor.white, for: .normal)
        timeBtn.setTitleColor(UIColor.black, for: .normal)
        let ss = (timeBtn.currentTitle ?? "").components(separatedBy: ":")
        let hh = ss[0]
        let mm = ss[1]
        if hh.hasPrefix("0") {
            pickerIndex1 = Int(hh.replacingOccurrences(of: "0", with: "")) ?? 0
        }else{
            pickerIndex1 = Int(hh) ?? 0
        }
        if mm.hasPrefix("0") {
            pickerIndex2 = Int(mm.replacingOccurrences(of: "0", with: "")) ?? 0
        }else{
            pickerIndex2 = Int(mm) ?? 0
        }
        timePickerView.selectRow(pickerIndex1, inComponent: 0, animated: false)
        timePickerView.selectRow(pickerIndex2, inComponent: 1, animated: false)
    }
    
    
    @IBAction func selectTimeHandle(_ sender: Any) {
       showTimeView()
    }
    
    @IBAction func okHandle(_ sender: Any) {
        let dateTimeStr = (dateBtn.currentTitle ?? "")  + " " + (timeBtn.currentTitle ?? "")
        selectCallBack?(Int(df1.date(from: dateTimeStr)!.timeIntervalSince1970), dateTimeStr)
        dismiss(animated: true)
    }
    
    @IBAction func cancelHandle(_ sender: Any) {
        dismiss(animated: true)
    }
    
    @IBAction func nextMonthHandle(_ sender: Any) {
        if let nextMonth = gregorian?.date(byAdding: .month, value: 1, to: self.calender.currentPage, options: .wrapComponents) {
            calender.setCurrentPage(nextMonth, animated: true)
        }
    }
    
    @IBAction func lastMonthHandle(_ sender: Any) {
        if let lastMonth = gregorian?.date(byAdding: .month, value: -1, to: self.calender.currentPage, options: .wrapComponents) {
            calender.setCurrentPage(lastMonth, animated: true)
        }
    }
    
    lazy var df: DateFormatter = {
        let temp = DateFormatter()
        temp.dateFormat = "yyyy年M月"
        return temp
    }()
    
    lazy var df1: DateFormatter = {
        let temp = DateFormatter()
        temp.dateFormat = "yyyy年M月d日 HH:mm"
        return temp
    }()
    
    lazy var df2: DateFormatter = {
        let temp = DateFormatter()
        temp.dateFormat = "yyyy年M月"
        return temp
    }()
    
    lazy var df3: DateFormatter = {
        let temp = DateFormatter()
        temp.dateFormat = "yyyy年M月d日"
        return temp
    }()
}

extension ManSelectDateTimeVC: FSCalendarDelegate, FSCalendarDataSource, FSCalendarDelegateAppearance {
    //日期cell被选中
    func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
        dateBtn.setTitle(df3.string(from: date), for: .normal)
        currentDate = date
        calendar.reloadData()
        showTimeView()
        
    }
    
    //月份page发生改变
    func calendarCurrentPageDidChange(_ calendar: FSCalendar) {
        yearMonthLabel.text = df.string(from: calendar.currentPage)
    }
    
//    func maximumDate(for calendar: FSCalendar) -> Date {
//        Date()
//    }
    
    //cell即将显示
    func calendar(_ calendar: FSCalendar, willDisplay cell: FSCalendarCell, for date: Date, at monthPosition: FSCalendarMonthPosition) {
//        if cell.dateIsToday {
//            cell.titleLabel.text = "今"
//        }
//        let m1 = calendar.gregorian.component(.month, from: date)
//        let m2 = calendar.gregorian.component(.month, from: calendar.currentPage)
//        if m2 != m1 {//非当月日期不显示
//            cell.titleLabel.textColor = UIColor.white.withAlphaComponent(0.5)
//        }
    }

    //未来日期不可交互、非当前page月份的日期不可选中
    func calendar(_ calendar: FSCalendar, shouldSelect date: Date, at monthPosition: FSCalendarMonthPosition) -> Bool {
//        let day = calendar.gregorian.dateComponents([.day], from: calendar.formatter.date(from: calendar.formatter.string(from: Date()))!, to: date).day ?? 0
//        let m1 = calendar.gregorian.component(.month, from: date)
//        let m2 = calendar.gregorian.component(.month, from: calendar.currentPage )
//        return day <= 0 && m1 == m2
        
//        let str = dateFormatter2.string(from: date)
//        guard let mm = LXTYQBirthdayHelper.shared.getLocalList().first(where: {$0.ts == Int(dateFormatter2.date(from: str)!.timeIntervalSince1970)})  else { return false}
        return true
    }
    
    //选中时的背景颜色
    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, fillSelectionColorFor date: Date) -> UIColor? {
        return .black
    }
    
    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, fillDefaultColorFor date: Date) -> UIColor? {
//        let timestamp = Int(dateFormatter2.date(from: dateFormatter2.string(from: date))!.timeIntervalSince1970)
//        if let mm = ZHNoteManager.shared.notes.first(where: {$0.timestamp == timestamp}) {
//            if mm.status == 1 {
//                return UIColor.init(hex: 0xFEAFE3)
//            }else if mm.status == 2 {
//                return UIColor.init(hex: 0xD3F427)
//            }
//        }
        let ts1 = Int(df3.date(from: df3.string(from: date))!.timeIntervalSince1970)
        let ts2 = Int(df3.date(from: df3.string(from: currentDate))!.timeIntervalSince1970)
        if ts1 == ts2 {
            return .black
        }
        return nil
    }
    
    //选中时的日期颜色
    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, titleSelectionColorFor date: Date) -> UIColor? {
        return .white
    }
    
    //默认的日期颜色
    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, titleDefaultColorFor date: Date) -> UIColor? {
//        let day = calendar.gregorian.dateComponents([.day], from: calendar.formatter.date(from: calendar.formatter.string(from: Date()))!, to: date).day ?? 0
//        if day > 0  {//未来日期
//            return .white.withAlphaComponent(0.4)
//        }
//        if calendar.gregorian.isDateInToday(date)  {
//            return .black
//        }
//        let tt = Int(dateFormatter2.date(from: dateFormatter2.string(from: date))!.timeIntervalSince1970)
//        if let mm = ZHNoteManager.shared.notes.first(where: {$0.timestamp == tt}) {
//            return .black
//        }
        return .white
    }
    
 
}

extension ManSelectDateTimeVC: UIPickerViewDelegate, UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        2
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 {
            return 24
        }
        return 60
    }
//
//    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
//        if row < 10 {
//            return "0\(row)"
//        }
//        return "\(row)"
//    }
    
    func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
        if row < 10 {
            return NSAttributedString(string: "0\(row)", attributes: [.foregroundColor: UIColor.white, .font : UIFont.systemFont(ofSize: 15)])
        }
        return NSAttributedString(string: "\(row)", attributes: [.foregroundColor: UIColor.white, .font : UIFont.systemFont(ofSize: 15)])
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if component == 0 {
            pickerIndex1 = row
        }else {
            pickerIndex2 = row
        }
        timeBtn.setTitle(String(format: "%02d:%02d", pickerIndex1, pickerIndex2), for: .normal)
    }
}
